package com.rico.smart.adapter;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.rico.smart.R;
import com.rico.smart.device.Device;
import com.rico.smart.message.IMessage;
import com.rico.smart.message.ImageMessage;
import com.rico.smart.utils.BitmapUtils;
import com.rico.smart.utils.FileUtils;
import com.rico.smart.utils.HandlerUtils;
import com.rico.smart.utils.ProgressDialogUtils;
import com.rico.smart.view.LoginDeviceDialog;

import java.io.File;
import java.io.IOException;
import java.util.List;


import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.model.PhotoInfo;

public class DeviceAdapter extends BaseAdapter {
    private String TAG = "DeviceAdapter";
    // 返回集合数据的数量
    private Context context;
    private List<Device> list;


    private ProgressDialog progressDialog;

    public DeviceAdapter(Context context, List<Device> datas) {
        this.context = context;
        this.list = datas;
    }

    @Override
    public int getCount() {
        return list.size();
    }

    //返回指定下标对应的数据对象
    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return 0;
    }

    /**
     * 返回指定下标对应的item的view对象
     * position：下标
     * convertview：可重复利用的控件
     * parent：ListView对象
     */
    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        //加载item的布局，得到View对象
        final Device device = list.get(position);
        if (convertView == null) {    //如果直接创建，很有可能照成应用崩毁
            convertView = View.inflate(context, R.layout.device_item, null);
            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (list.get(position).isOnline()) {
                        openPicturesSelected(list.get(position));
                    } else {
                        LoginDeviceDialog LoginDeviceDialog = new LoginDeviceDialog((Activity) context, device);
                        LoginDeviceDialog.show();
                    }
                }
            });
        }


        ImageView imageView = (ImageView) convertView.findViewById(R.id.img);
        TextView tv1 = (TextView) convertView.findViewById(R.id.tv);
        tv1.setText(device.getDeviceInfo().getDeviceId());
        TextView tv2 = (TextView) convertView.findViewById(R.id.tv_device_hint);
        tv2.setText(device.getDeviceInfo().getLocalIP() + "(" + (device.isOnline() ? "在线" : "已断开") + ")");
        if (device.isOnline()) {
            tv2.setTextColor(Color.GREEN);
        } else {
            tv2.setTextColor(Color.GRAY);
        }
        return convertView;
    }

    public void openPicturesSelected(final Device device) {
        GalleryFinal.openGalleryMuti(1, 8, new GalleryFinal.OnHanlderResultCallback() {
            @Override
            public void onHanlderSuccess(int reqeustCode, final List<PhotoInfo> resultList) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        for (PhotoInfo item : resultList) {
                            File file = new File(item.getPhotoPath());
                            byte bytes[] = BitmapUtils.readFile(item.getPhotoPath());
                            ImageMessage message = new ImageMessage();
                            message.setImageBytes(bytes);
                            message.setFileName(file.getName());
                            message.setExtName(FileUtils.getExtName(file));
                            message.setReceiver(device.getDeviceInfo().getDeviceId());
                            message.setDeviceSessionId(device.getSessionId());
                            try {
                                HandlerUtils.sendHandlerMessage(mHandler, 3, "正在上传图片："+file.getName());
                                IMessage iMessage = device.send(message,60000);
                                if(iMessage==null){
                                    HandlerUtils.sendHandlerMessage(mHandler, 2, file.getName());
                                }else{
                                    switch (iMessage.getMessageType()) {
                                        case SUCCESS:
                                            HandlerUtils.sendHandlerMessage(mHandler, 1, file.getName());
                                            break;
                                        case ERROR:
                                            HandlerUtils.sendHandlerMessage(mHandler, 2, file.getName());
                                            break;
                                        default:
                                            break;
                                    }
                                }
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }).start();

            }

            @Override
            public void onHanlderFailure(int requestCode, String errorMsg) {

            }
        });
    }

    Handler mHandler=new Handler() {

        @Override
        public void handleMessage(Message msg) {
            if(msg.what!=3) {
                progressDialog.hide();
            }
           switch (msg.what){
               case 1:
                   Toast.makeText((Activity)context, "上传成功"+msg.obj, Toast.LENGTH_LONG).show();
                   break;
               case 2:
                   Toast.makeText((Activity)context, "上传失败"+msg.obj, Toast.LENGTH_LONG).show();
                   break;
               case 3:
                   progressDialog= ProgressDialogUtils.loading((Activity)context,"",(String)msg.obj);
                   break;
                   default:
                       break;
           }
        }
    };

}